/**
 * 统一API请求工具类
 * 整合Ajax、Fetch、Axios三种请求方式，提供统一的API接口
 */

/**
 * 请求方式枚举
 */
const RequestType = {
  AJAX: 'ajax',
  FETCH: 'fetch',
  AXIOS: 'axios'
};

/**
 * 统一API客户端类
 */
class UnifiedApiClient {
  constructor(config = {}) {
    this.defaultType = config.defaultType || RequestType.AXIOS;
    
    // 初始化各种客户端
    this.ajaxClient = new AjaxClient(config);
    this.fetchClient = new FetchClient(config);
    this.axiosClient = new AxiosClient(config);
  }

  /**
   * 发送请求
   */
  async request(config) {
    const requestType = config.type || this.defaultType;
    
    switch (requestType) {
      case RequestType.AJAX:
        return this.ajaxClient.request(config);
      case RequestType.FETCH:
        return this.fetchClient.request(config);
      case RequestType.AXIOS:
        return this.axiosClient.request(config);
      default:
        throw new Error(`Unsupported request type: ${requestType}`);
    }
  }

  /**
   * GET请求
   */
  async get(url, params, config) {
    return this.request({
      ...config,
      url,
      method: 'GET',
      params
    });
  }

  /**
   * POST请求
   */
  async post(url, data, config) {
    return this.request({
      ...config,
      url,
      method: 'POST',
      data
    });
  }

  /**
   * PUT请求
   */
  async put(url, data, config) {
    return this.request({
      ...config,
      url,
      method: 'PUT',
      data
    });
  }

  /**
   * DELETE请求
   */
  async delete(url, config) {
    return this.request({
      ...config,
      url,
      method: 'DELETE'
    });
  }

  /**
   * PATCH请求
   */
  async patch(url, data, config) {
    return this.request({
      ...config,
      url,
      method: 'PATCH',
      data
    });
  }
}

/**
 * 创建统一API客户端
 */
function createUnifiedApiClient(config) {
  return new UnifiedApiClient(config);
}

/**
 * 快速请求方法
 */
const api = {
  /**
   * 创建统一API客户端
   */
  createClient: createUnifiedApiClient,
  
  /**
   * 快速GET请求
   */
  get: async (url, params, type) => {
    const client = createUnifiedApiClient();
    return client.get(url, params, { type });
  },
  
  /**
   * 快速POST请求
   */
  post: async (url, data, type) => {
    const client = createUnifiedApiClient();
    return client.post(url, data, { type });
  },
  
  /**
   * 快速PUT请求
   */
  put: async (url, data, type) => {
    const client = createUnifiedApiClient();
    return client.put(url, data, { type });
  },
  
  /**
   * 快速DELETE请求
   */
  delete: async (url, type) => {
    const client = createUnifiedApiClient();
    return client.delete(url, { type });
  }
};

// 导出
if (typeof module !== 'undefined' && module.exports) {
  module.exports = { UnifiedApiClient, createUnifiedApiClient, api, RequestType };
} else if (typeof window !== 'undefined') {
  window.api = api;
  window.UnifiedApiClient = UnifiedApiClient;
  window.createUnifiedApiClient = createUnifiedApiClient;
  window.RequestType = RequestType;
}
